package com.botao.tip.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.botao.tip.entity.Department;
import com.botao.tip.entity.LoginCount;
import com.botao.tip.entity.User;
import com.botao.tip.service.DepartmentService;
import com.botao.tip.service.IUserService;
import com.botao.tip.utils.*;
import com.botao.tip.convert.UserConvert;
import com.botao.tip.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author cbt28
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("register")
    public AjaxResult register(String username, String password, String role) {
        if (username == null || "".equals(username) || password == null || "".equals(password) || role == null || "".equals(role)) {
            return AjaxResult.error(300, "参数不能为空！");
        }
        if (userService.userExists(username)) {
            return AjaxResult.error(500, "该用户名已经被注册！");
        }

        //约定大于配置
        User user = new User();
        user.setId(null);
        user.setUsername(username);
        user.setTrueName("匿名用户");
        user.setAddress("火星");
        String salt = UUIDUtil.create();
        //随机盐
        user.setSalt(salt);
        user.setPassword(Md5Util.encodeByMd5(password, salt));
        int iRole = Integer.parseInt(role);
        if (iRole < 0 || iRole > 3) {
            iRole = 0;
        }
        user.setRole(iRole);
        user.setCreated(new Date());
        boolean save = userService.save(user);
        return save ? AjaxResult.success() : AjaxResult.error();
    }

    @GetMapping("get/{id}")
    public AjaxResult getOne(@PathVariable String id) {
        User user = userService.getOne(new QueryWrapper<User>().eq("id", id));
        if (user == null) {
            return AjaxResult.error();
        }
        UserVo userVo = UserConvert.convertToUserVo(user);
        return AjaxResult.success(userVo);
    }

    @GetMapping("all")
    public AjaxResult getAll(@RequestParam int currentPage, @RequestParam int pageSize) {
        Page<User> page = userService.page(new Page<>(currentPage, pageSize));

        List<User> records = page.getRecords();
        List<UserVo> userList = new ArrayList<>();
        records.forEach(user -> {
            userList.add(UserConvert.convertToUserVo(user));
        });

        long total = page.getTotal();
        long current = page.getCurrent();
        long size = page.getSize();
        boolean hasNext = page.hasNext();
        boolean hasPrevious = page.hasPrevious();

        HashMap<Object, Object> map = new HashMap<>();

        map.put("user", userList);
        map.put("total", total);
        map.put("current", current);
        map.put("size", size);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return AjaxResult.success(map);
    }

    @DeleteMapping("delete/{id}")
    public AjaxResult delete(@PathVariable String id) {
        return userService.removeById(id) ? AjaxResult.success() : AjaxResult.error();
    }

    @RequestMapping("update/")
    public AjaxResult update(String id,
                             String username,
                             String trueName,
                             String gender,
                             String password,
                             String address,
                             String roleId,
                             int departmentId) {
        boolean flag = userService.updateUser(id, username, trueName, gender, password, address, roleId, departmentId);
        return flag ? AjaxResult.success() : AjaxResult.error(500, "更新失败");
    }

    @PostMapping("status")
    public AjaxResult changeStatus(String id, String status) {
        boolean flag;
        User user = new User();
        try {
            user.setStatus(Integer.parseInt(status));
        } catch (Exception e) {
            return AjaxResult.error("错误的状态码！");
        }

        flag = userService.update(user, new UpdateWrapper<User>().eq("id", id));
        return flag ? AjaxResult.success() : AjaxResult.error();
    }

    @GetMapping("role/count")
    public AjaxResult roleCount() {
        return AjaxResult.success(userService.roleCount());
    }

    @GetMapping("/fuzzy/query")
    public AjaxResult userFuzzyQuery(String input) {
        System.out.println(input);
        if (input == null) {
            return AjaxResult.error("无输入值.");
        }
        List<User> users = userService.userFuzzyQuery(input);
        List<UserVo> result = new ArrayList<>();
        for (User user : users) {
            UserVo userVo = UserConvert.convertToUserVo(user);
            result.add(userVo);
        }
        return AjaxResult.success(result);
    }

/*    @GetMapping("weekView")
    public AjaxResult weekView() {

    }*/

}
